/**
 * @Project : ProgrammingExercises
 * @Package : Leetcode
 * @File : Q0094.java
 * @Author : WangRuoyu
 * @Date 2022/12/27 15:23
 */

package leetcode;

import util.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Deque;

public class Q0094 {

    /*** 递归 ***/
//    private void inorderTravel(TreeNode root, List<Integer> res) {
//        if (root.left != null) {
//            inorderTravel(root.left, res);
//        }
//        res.add(root.val);
//        if (root.right != null) {
//            inorderTravel(root.right, res);
//        }
//    }
//
//    public List<Integer> inorderTraversal(TreeNode root) {
//        List<Integer> res = new ArrayList<>();
//        if (root == null) {
//            return res;
//        }
//        inorderTravel(root, res);
//        return res;
//    }

    /*** 迭代 ***/
//    public List<Integer> inorderTraversal(TreeNode root) {
//        List<Integer> res = new ArrayList<>();
//        Deque<TreeNode> stk = new LinkedList<TreeNode>();
//
//        while (!stk.isEmpty() || root != null) {
//            while (root != null) {
//                stk.push(root);
//                root = root.left;
//            }
//            root = stk.pop();
//            res.add(root.val);
//            root = root.right;
//        }
//        return res;
//    }

    /*** Morris 中序遍历 ***/
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        TreeNode predecessor = null;

        while (root != null) {
            if (root.left == null) {
                res.add(root.val);
                root = root.right;
            } else {
                predecessor = root.left;
                while ((predecessor.right != root) && (predecessor.right != null)) {
                    predecessor = predecessor.right;
                }
                if (predecessor.right == null) {
                    predecessor.right = root;
                    root = root.left;
                } else {
                    res.add(root.val);
                    predecessor.right = null;
                    root = root.right;
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Q0094 sl = new Q0094();
        TreeNode root = new TreeNode(1, new TreeNode(2), new TreeNode(3));
        List<Integer> res = sl.inorderTraversal(root);
        for (int i = 0; i < res.size(); i++) {
            System.out.println(res.get(i));
        }
    }
}